<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>论文管理系统</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        /* 全局样式 */
        body {
            background: linear-gradient(to bottom right, #e6f0ff, #d0e6f6);
            font-family: 'Poppins', sans-serif;
            color: #333;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: background 0.5s ease;
        }

        .container {
            max-width: 1200px;
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            padding: 30px;
            animation: fadeIn 0.8s ease-in-out;
            width: 100%;
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
            font-weight: 600;
            color: #333;
        }

        /* 按钮样式 */
        .btn {
            border-radius: 25px;
            padding: 10px 20px;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .btn-success {
            background: linear-gradient(to right, #34c759, #30c270);
            color: #fff;
            border: none;
        }

        .btn-success:hover {
            background: linear-gradient(to right, #30c270, #34c759);
        }

        .btn-primary {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            color: #fff;
            border: none;
        }

        .btn-primary:hover {
            background: linear-gradient(to right, #2575fc, #6a11cb);
        }

        .btn-danger {
            background: linear-gradient(to right, #ff6a6a, #ff3d3d);
            color: #fff;
            border: none;
        }

        .btn-danger:hover {
            background: linear-gradient(to right, #ff3d3d, #ff6a6a);
        }

        /* 表格样式 */
        .table {
            margin-top: 20px;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            transition: opacity 0.5s ease;
        }

        .table th {
            background: #6a11cb;
            color: #fff;
            text-align: center;
            font-weight: 600;
            transition: background 0.3s ease;
        }

        .table th:hover {
            background: #2575fc;
        }

        .table td {
            text-align: center;
            vertical-align: middle;
        }

        .table tbody tr:hover {
            background-color: #f1f1f1;
            transition: background-color 0.3s ease;
        }

        /* 分页样式 */
        .pagination {
            justify-content: center;
            margin-top: 20px;
        }

        .pagination .page-link {
            color: #6a11cb;
            transition: color 0.3s ease, background-color 0.3s ease;
        }

        .pagination .page-link:hover {
            color: #fff;
            background-color: #6a11cb;
        }

        .pagination .active .page-link {
            background-color: #6a11cb;
            border-color: #6a11cb;
            color: #fff;
        }

        /* 模态框样式 */
        .modal-content {
            border-radius: 15px;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .modal-header {
            background: #6a11cb;
            color: #fff;
            border-bottom: none;
            border-top-left-radius: 15px;
            border-top-right-radius: 15px;
        }

        .modal-footer .btn-secondary {
            background: #ddd;
            color: #333;
            border: none;
            border-radius: 25px;
            padding: 10px 20px;
            transition: background 0.3s ease;
        }

        .modal-footer .btn-secondary:hover {
            background: #ccc;
        }

        .modal-footer .btn-primary {
            border-radius: 25px;
        }

        /* 表单控件样式 */
        .form-control {
            border-radius: 15px;
            border: 1px solid #ddd;
            padding: 10px 15px;
            font-size: 14px;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }

        .form-control:focus {
            border-color: #6a11cb;
            box-shadow: 0 0 5px rgba(106, 17, 203, 0.5);
        }

        /* 跳转到页面功能样式 */
        .jump-to-page {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            margin-bottom: 15px;
            gap: 10px;
        }

        .jump-to-page input {
            width: 80px;
        }

        /* 动画 */
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
<div class="container">
    <h1>论文管理系统</h1>

    <!-- 跳转到页面功能 -->
    <div class="jump-to-page">
        <label for="jumpPageInput" class="mr-2">跳转到第</label>
        <input type="number" class="form-control" id="jumpPageInput" min="1" placeholder="页码">
        <button class="btn btn-primary" id="jumpPageBtn">跳转</button>
    </div>

    <button class="btn btn-success mb-3" id="addPaperBtn">新增论文</button>
    <table class="table table-bordered table-striped" id="paper-table">
        <thead>
        <tr>
            <th>编号</th>
            <th>标题</th>
            <th>作者</th>
            <th>摘要</th>
            <th>日期</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过jQuery动态插入 -->
        </tbody>
    </table>
    <!-- 分页导航 -->
    <nav>
        <ul class="pagination" id="pagination">
            <!-- 分页按钮将通过jQuery动态插入 -->
        </ul>
    </nav>
</div>

<!-- 编辑模态框 -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑论文</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <input type="hidden" id="editPaperId">
                    <div class="form-group">
                        <label for="editTitle">标题</label>
                        <input type="text" class="form-control" id="editTitle" required>
                    </div>
                    <div class="form-group">
                        <label for="editAuthor">作者</label>
                        <input type="text" class="form-control" id="editAuthor" required>
                    </div>
                    <div class="form-group">
                        <label for="editAbstract">摘要</label>
                        <textarea class="form-control" id="editAbstract" rows="3" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="editPubdate">日期</label>
                        <input type="date" class="form-control" id="editPubdate" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="saveEditBtn">保存修改</button>
            </div>
        </div>
    </div>
</div>

<!-- 新增模态框 -->
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">新增论文</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addForm">
                    <div class="form-group">
                        <label for="addTitle">标题</label>
                        <input type="text" class="form-control" id="addTitle" required>
                    </div>
                    <div class="form-group">
                        <label for="addAuthor">作者</label>
                        <input type="text" class="form-control" id="addAuthor" required>
                    </div>
                    <div class="form-group">
                        <label for="addAbstract">摘要</label>
                        <textarea class="form-control" id="addAbstract" rows="3" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="addPubdate">日期</label>
                        <input type="date" class="form-control" id="addPubdate" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="saveAddBtn">保存论文</button>
            </div>
        </div>
    </div>
</div>

<!-- jQuery, Popper.js, Bootstrap JS, SweetAlert2 JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function () {
        const apiUrl = 'http://localhost:8080/paper';
        const rowsPerPage = 20;
        let currentPage = 1;
        let totalPages = 1;
        let papersData = [];

        // 禁用页面滚动
        function lockBodyScroll() {
            document.body.style.overflow = 'hidden';
        }

        // 启用页面滚动
        function unlockBodyScroll() {
            document.body.style.overflow = '';
        }

        // 获取论文数据
        function fetchPapers() {
            $.ajax({
                url: `${apiUrl}/paperList`,
                method: 'GET',
                dataType: 'json',
                success: function (data) {
                    // 假设最新的论文在数组的前面
                    papersData = data;
                    totalPages = Math.ceil(papersData.length / rowsPerPage);
                    currentPage = 1; // 重置到第一页
                    renderTable();
                    renderPagination();
                },
                error: function (xhr, status, error) {
                    console.error('获取数据时出错:', error);
                    Swal.fire('错误', '无法获取论文数据，请稍后再试。', 'error');
                }
            });
        }

        // 渲染表格
        function renderTable() {
            const tbody = $('#paper-table tbody');
            tbody.fadeOut(200, function () {
                tbody.empty();

                const start = (currentPage - 1) * rowsPerPage;
                const end = start + rowsPerPage;
                const paginatedData = papersData.slice(start, end);

                paginatedData.forEach(function (paper, index) {
                    const rowNumber = start + index + 1; // 计算全局编号
                    const row = `
                <tr>
                    <td>${rowNumber}</td>
                    <td>${paper.title}</td>
                    <td>${paper.author}</td>
                    <td>${paper.abstract1 || '无摘要'}</td>
                    <td>${paper.pubdate || '未指定'}</td>
                    <td>
                        <button class="btn btn-primary edit-btn" data-id="${paper.id}">编辑</button>
                        <button class="btn btn-danger delete-btn" data-id="${paper.id}">删除</button>
                    </td>
                </tr>
            `;
                    tbody.append(row);
                });

                tbody.fadeIn(200);
                bindEvents();
            });
        }


        // 渲染分页按钮
        function renderPagination() {
            const pagination = $('#pagination');
            pagination.fadeOut(200, function () {
                pagination.empty();

                // 首页按钮
                if (currentPage > 1) {
                    pagination.append(`<li class="page-item">
                            <a class="page-link" href="#" aria-label="首页" data-page="1">
                                <span aria-hidden="true">&laquo;&laquo;</span>
                            </a>
                        </li>`);
                } else {
                    pagination.append(`<li class="page-item disabled">
                            <a class="page-link" href="#" aria-label="首页">
                                <span aria-hidden="true">&laquo;&laquo;</span>
                            </a>
                        </li>`);
                }

                // Previous Button
                const prevDisabled = currentPage === 1 ? 'disabled' : '';
                pagination.append(`<li class="page-item ${prevDisabled}">
                        <a class="page-link" href="#" aria-label="上一页" data-page="${currentPage - 1}">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>`);

                // Determine the range of page numbers to display
                let startPage = 1;
                let endPage = totalPages;

                if (totalPages > 5) { // 最多显示5个页码
                    if (currentPage <= 3) {
                        startPage = 1;
                        endPage = 5;
                    } else if (currentPage + 2 >= totalPages) {
                        startPage = totalPages - 4;
                        endPage = totalPages;
                    } else {
                        startPage = currentPage - 2;
                        endPage = currentPage + 2;
                    }
                }

                // Page Numbers
                for (let i = startPage; i <= endPage; i++) {
                    const active = i === currentPage ? 'active' : '';
                    pagination.append(`<li class="page-item ${active}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>`);
                }

                // Next Button
                const nextDisabled = currentPage === totalPages ? 'disabled' : '';
                pagination.append(`<li class="page-item ${nextDisabled}">
                        <a class="page-link" href="#" aria-label="下一页" data-page="${currentPage + 1}">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>`);

                // 末页按钮
                if (currentPage < totalPages) {
                    pagination.append(`<li class="page-item">
                            <a class="page-link" href="#" aria-label="末页" data-page="${totalPages}">
                                <span aria-hidden="true">&raquo;&raquo;</span>
                            </a>
                        </li>`);
                } else {
                    pagination.append(`<li class="page-item disabled">
                            <a class="page-link" href="#" aria-label="末页">
                                <span aria-hidden="true">&raquo;&raquo;</span>
                            </a>
                        </li>`);
                }

                // 绑定点击事件
                $('.page-link').off().click(function (e) {
                    e.preventDefault();
                    const selectedPage = parseInt($(this).data('page'));
                    if (selectedPage >= 1 && selectedPage <= totalPages && selectedPage !== currentPage) {
                        currentPage = selectedPage;
                        renderTable();
                        renderPagination();
                        // 平滑滚动到表格顶部
                        $('html, body').animate({
                            scrollTop: $("#paper-table").offset().top - 20
                        }, 500);
                    }
                });

                pagination.fadeIn(200);
            });
        }

        // 绑定编辑和删除按钮事件
        function bindEvents() {
            // 编辑按钮事件
            $('.edit-btn').off().click(function () {
                const paperId = $(this).data('id');
                $.ajax({
                    url: `${apiUrl}/getPaperById`,
                    method: 'GET',
                    data: { id: paperId },
                    dataType: 'json',
                    success: function (data) {
                        $('#editPaperId').val(data.id);
                        $('#editTitle').val(data.title);
                        $('#editAuthor').val(data.author);
                        $('#editAbstract').val(data.abstract1);
                        $('#editPubdate').val(data.pubdate);
                        $('#editModal').modal('show');
                    },
                    error: function (xhr, status, error) {
                        console.error('获取论文时出错:', error);
                        Swal.fire('错误', '无法获取论文信息，请稍后再试。', 'error');
                    }
                });
            });

            // 删除按钮事件
            $('.delete-btn').off().click(function () {
                const paperId = $(this).data('id');
                lockBodyScroll();
                Swal.fire({
                    title: '确定要删除这篇论文吗？',

                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: '删除',
                    cancelButtonText: '取消'
                }).then((result) => {
                    unlockBodyScroll();
                    if (result.isConfirmed) {
                        $.ajax({
                            url: `${apiUrl}/delete?id=${paperId}`,
                            method: 'DELETE',
                            success: function () {
                                Swal.fire('删除成功', '论文已成功删除', 'success');
                                fetchPapers();
                            },
                            error: function (xhr, status, error) {
                                console.error('删除论文时出错:', error);
                                Swal.fire('删除失败', '无法删除论文，请稍后再试。', 'error');
                            }
                        });
                    }
                });
            });
        }

        // 保存编辑按钮事件
        $('#saveEditBtn').off().click(function () {
            const updatedPaper = {
                id: $('#editPaperId').val(),
                title: $('#editTitle').val(),
                author: $('#editAuthor').val(),
                abstract1: $('#editAbstract').val(),
                pubdate: $('#editPubdate').val()
            };

            $.ajax({
                url: `${apiUrl}/update`,
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(updatedPaper),
                success: function () {
                    Swal.fire('修改成功', '论文信息已成功更新', 'success');
                    $('#editModal').modal('hide');
                    fetchPapers();
                },
                error: function (xhr, status, error) {
                    console.error('更新论文时出错:', error);
                    Swal.fire('修改失败', '无法更新论文信息，请稍后再试。', 'error');
                }
            });
        });

        // 新增论文按钮事件
        $('#addPaperBtn').click(function () {
            $('#addModal').modal('show');
        });

        // 保存新增论文按钮事件
        $('#saveAddBtn').click(function () {
            const newPaper = {
                title: $('#addTitle').val(),
                author: $('#addAuthor').val(),
                abstract1: $('#addAbstract').val(),
                pubdate: $('#addPubdate').val()
            };

            $.ajax({
                url: `${apiUrl}/add`,
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(newPaper),
                dataType: 'json', // 确保期待JSON响应
                success: function (response) {
                    Swal.fire('新增成功', '论文已成功新增', 'success');
                    $('#addModal').modal('hide');
                    // 将新论文插入到 papersData 的开头
                    papersData.unshift(response);
                    totalPages = Math.ceil(papersData.length / rowsPerPage);
                    currentPage = 1; // 新增后重置到第一页
                    renderTable();
                    renderPagination();
                },
                error: function (xhr, status, error) {
                    console.error('新增失败:', status, error);
                    console.error('响应内容:', xhr.responseText);
                    Swal.fire('新增失败', '无法新增论文，请稍后再试。', 'error');
                }
            });
        });

        // 跳转到指定页面按钮事件
        $('#jumpPageBtn').click(function () {
            const jumpPage = parseInt($('#jumpPageInput').val());
            if (isNaN(jumpPage) || jumpPage < 1 || jumpPage > totalPages) {
                Swal.fire('错误', `请输入一个有效的页码（1 - ${totalPages}）。`, 'error');
            } else {
                currentPage = jumpPage;
                renderTable();
                renderPagination();
                // 平滑滚动到表格顶部
                $('html, body').animate({
                    scrollTop: $("#paper-table").offset().top - 20
                }, 500);
            }
        });

        // 允许按Enter键跳转页面
        $('#jumpPageInput').keypress(function (e) {
            if (e.which === 13) { // Enter键
                $('#jumpPageBtn').click();
            }
        });

        // 初始化获取论文数据
        fetchPapers();
    });
</script>
</body>
</html>
